 var AutoHref = {toString: function(){return '[AutoHref Object]';}};

(function(ah){
	
	var  initLinks, selectedTextRangeObj, clearHrefAlertButton, siteWindow, contextUrl = '<%=contextUrl%>';
	
	var TB_WIDTH =  630; 
	var TB_HEIGHT = 440;
		
	var tb_remove = function(){
	 	$("#AH_TB_window").fadeOut("fast",function(){$('#AH_TB_window,#AH_TB_overlay').trigger("unload").unbind().remove();});
		document.onkeydown = "";
		document.onkeyup = "";
		return false;
	}
	
	var tb_detectMacXFF = function () {
	  var userAgent = navigator.userAgent.toLowerCase();
	  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
	    return true;
	  }
	}
	
	var tb_position = function() {
		$("#AH_TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px',marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
		$("#TB_window").css({});
	}
	
	var walkElements = function(node, depth, textproc) {
	    var skipre = /^(script|style|textarea|a)/i;
	    var count = 0;
	    while (node && depth > 0) {
	        count ++;
	        if (count >= 1000) {
	            var handler = function() {
	                walkElements(node, depth, textproc);
	            };
	            setTimeout(handler, 50);
	            return;
	        }
	
	        if (node.nodeType == 1) {
	        	if (!skipre.test(node.tagName) && node.childNodes.length > 0) {
	                node = node.childNodes[0];
	                depth ++;
	                continue;
	            }
	        } else if (node.nodeType == 3) {
	            node = textproc(node);
	        }
	
	        if (node.nextSibling) {
	            node = node.nextSibling;
	        } else {
	            while (depth > 0) {
	                node = node.parentNode;
	                depth --;
	                if (node.nextSibling) {
	                    node = node.nextSibling;
	                    break;
	                }
	            }
	        }
	    }
	};
	
	var selectedTextRange = function()
	{
	  	var hrefAlertButton;
	  	clearHrefAlertButton = function(event){
	  		document.normalize();
  			if(event && event.target == hrefAlertButton) return;
  			hrefAlertButton && hrefAlertButton.parentNode && hrefAlertButton.parentNode.removeChild(hrefAlertButton);
		  	event && event.target.parentNode.focus();
		    hrefAlertButton = null;
  			
	  	}
	  	  
	    var doSelect = function(){
	    	
		    var selection = window.getSelection();
			var selectionString = selection.toString().replace(/^\s+|\s+$/g, '');
			var mousedownContainer = selection.anchorNode;
            var mouseupContainer = selection.focusNode;
			var selectionOffset = (selection.anchorOffset < selection.focusOffset) ? selection.anchorOffset : selection.focusOffset;
			var parentNodeTagName, parentNodeIndex, childNodeIndex;
			
			if(selectionString.length > 1){
 				
 				if((mousedownContainer == mouseupContainer) && (mouseupContainer.nodeType == 3) && (mouseupContainer.parentNode.nodeType == 1)){
					for(var i=0; !/\S/.test(mouseupContainer.nodeValue.charAt(selectionOffset + i)); i++){
						selectionOffset++;
					}
					parentNodeTagName = (mouseupContainer.parentNode) ? mouseupContainer.parentNode.nodeName : parentNodeTagName;
					
                    var arrDocumentGetElementsByTagName = document.getElementsByTagName(parentNodeTagName);
                    for(var i=0; i< arrDocumentGetElementsByTagName.length; i++){
                        if(arrDocumentGetElementsByTagName[i] == mouseupContainer.parentNode){
                            parentNodeIndex = i;
                            break;
                        }
                    }
                    for(var i=0; i< mouseupContainer.parentNode.childNodes.length; i++){
                        if(mouseupContainer.parentNode.childNodes[i] == mouseupContainer){
                            childNodeIndex = i;
                            break;
                        }
                    }
                    
                    clearHrefAlertButton();
                    hrefAlertButton = document.createElement("DIV");
                    hrefAlertButton.setAttribute("style","margin:-20px 0 0 -20px;position:absolute;display:inline;background:url(/static/hustle/i/href-alert.png);width:25px;height:29px;cursor:pointer;");
                    hrefAlertButton.setAttribute("onmousedown","AutoHref.showOverlay('request-link/" + encodeURIComponent(contextUrl).replace(/'/g,"%27").replace(/\//g,"%2F") + "/" +encodeURIComponent(selectionString).replace(/'/g,"%27").replace(/\//g,"%2F")+ "/" + parentNodeTagName +"/" + parentNodeIndex + "/"+ childNodeIndex + "/" + selectionOffset  + "');return false;");
                    var newRange = document.createRange();
				    newRange.setStart(mouseupContainer, selection.getRangeAt(0).endOffset);
				    newRange.insertNode(hrefAlertButton);
				    
				} 				
			}
	    }
	    
	    this.clearSelect = function(event){
	       
	       	clearHrefAlertButton(event);
	   	}
	   	this.endSelect = function(event){
	  		
	  		window.setTimeout(function(){doSelect()},100);
	  	}    
	    
	}
	
		
	ah.init = function(links){
	
		if(window.getSelection){
	        var blnRangeImplemented = document.implementation.hasFeature("Range", "2.0");
	        if(blnRangeImplemented){
	            selectedTextRangeObj = new selectedTextRange();
	            jQuery("body").bind("mouseup", selectedTextRangeObj.endSelect);
	            jQuery("*").bind("mousedown", selectedTextRangeObj.clearSelect);
	           	         
	        }else{
	            alert("Sorry, but your browser does not support the W3C Level 2 DOM Range API.");
	        }
	    }else{
	        alert("Sorry, but your browser does not support the window.getSelection() method.");
	    }
		initLinks = links;
		this.makeAnchors(initLinks);
	}
	
	ah.make = function(elm, query) {
	    if (!query || elm.childNodes.length == 0)
		return;
	
	    var qre = new Array();
	    for (var i = 0; i < query.length; i ++) {
	        query[i] = query[i].toLowerCase();
	    	qre.push(query[i]);
	    }
	
	    qre = new RegExp(qre.join("|"), "i");
	
	    var stylemapper = {};
	    for (var i = 0; i < query.length; i ++) {
	       	stylemapper[query[i]] = "test";
	    }
	
	    var textproc = function(node) {
	        var match = qre.exec(node.data);
	        if (match) {
	            var val = match[0];
	            var node2 = node.splitText(match.index);
	            var node3 = node2.splitText(val.length);
	            var span = node.ownerDocument.createElement('SPAN');
	            node.parentNode.replaceChild(span, node2);
	            span.className = stylemapper[val.toLowerCase()];
	            span.appendChild(node2);
	            return span;
	        } else {
	            return node;
	        }
	    };
	    
	    walkElements(elm.childNodes[0], 1, textproc);
	};
	
	ah.showOverlay = function(action){
				
		if(document.getElementById("TB_overlay") === null){
			$("body").append("<div id='AH_TB_overlay' style='position:fixed;z-index:100;top:0px;left:0px;height:100%;width:100%;'></div><div id='AH_TB_window' style='position:fixed;background:#ffffff;z-index:102;color:#000000;display:none;border:4px solid #525252;text-align:left;top:50%;left:50%;'></div>");
			$("#AH_TB_overlay").click(tb_remove);
		}
				
		if(tb_detectMacXFF()){
			$("#AH_TB_overlay").css({'background': 'url(macFFBgHack.png) repeat'});//use png overlay so hide flash
		}else{
			$("#AH_TB_overlay").css({
				'background-color':'#000',
				'filter': 'alpha(opacity=75)',
				'-moz-opacity': '0.75',
				'opacity': '0.75'
			});//use background and opacity
		}
		
		tb_position();
		var	iframeW = TB_WIDTH - 30;
		var	iframeH = TB_HEIGHT - 45;
		
		$("#AH_TB_window").append("<iframe frameborder='0' hspace='0' src='/hustle/frame/"+ action +"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='AutoHref.showIframe()' style='width:"+(iframeW + 29)+"px;height:"+(iframeH + 17)+"px;' > </iframe>");			

				
	}
	
	ah.makeAnchors = function(anchors){
		
		for(var i in anchors)
		{
			var anchor = anchors[i];
			
			with(anchor){
				var parentNode = document.getElementsByTagName(parentNodeTagName)[parentNodeIndex];
				
				var node = parentNode.childNodes[childNodeIndex];
				
				var node2 = node.splitText(selectionOffset);
		       	var node3 = node2.splitText(selectionString.length);
		        
		        var anchor = node.ownerDocument.createElement('A');
		        node.parentNode.replaceChild(anchor, node2);
		        //anchor.setAttribute("style","border-bottom:1px dotted #000");
		        anchor.setAttribute("id","ah-anchor-" +  id);
		        anchor.setAttribute("href", href);
		        anchor.setAttribute("onmouseover","$('div',this).css({display:'inline'})");
		        anchor.setAttribute("onmouseout","$('div',this).hide()");
		        anchor.appendChild(node2);
		       	var hrefEditButton = document.createElement("DIV");
		        hrefEditButton.setAttribute("style","display:none;margin:-20px 0 0 -20px;position:absolute;background:url(/static/hustle/i/href-alert.png);width:25px;height:29px;cursor:pointer;");
		        hrefEditButton.setAttribute("onmousedown","AutoHref.showOverlay('edit-link/"+id+"');return false;");
		        anchor.appendChild(hrefEditButton);
		        parentNode.focus();
		        clearHrefAlertButton();
		        tb_remove();
			}
		}
	}
	
	ah.removeAnchor = function(id, removeFrame){
		$("#ah-anchor-" + id).replaceWith($("#ah-anchor-" + id).text());
		document.normalize();
		if(removeFrame) tb_remove();
	}
	
	ah.showIframe = function (){
		$("#AH_TB_window").css({display:"block"});
	}
	
})(AutoHref);


AutoHref.init(<%=contextLinks.toSource()%>);




